package api;

import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-03-24
 * Time: 10:18
 */
// 点击注销, 则退出登陆, 将 session 中的 user删除
// HttpSession 没有一个直接用于删除的方法(Servlet 没有提供)
@WebServlet("/exit")
public class ExitLoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset = utf8");
        req.setCharacterEncoding("utf8");
        HttpSession session = req.getSession(false);
        if(session == null) {
            // 没有会话, 当前则为未登录状态
            resp.getWriter().write("{\"issuccess\":false}");
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            // 有会话, 但是没有 user 对象, 仍然认为是未登录状态
            resp.getWriter().write("{\"issuccess\":false}");
        }

        // 前端点击以后直接判断会话或者用户是否存在, 后端不需要返回其他东西
        // 删除会话中对应的 user
        session.removeAttribute("user"); // 破坏掉强制登录的条件之一让其强制返回登录
        resp.getWriter().write("{\"issuccess\":true}");
    }
}
